package secret.hehe.com.secret.Activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import secret.hehe.com.secret.R;
import secret.hehe.com.secret.Util.MessageService;
import secret.hehe.com.secret.Util.Util;

import static secret.hehe.com.secret.Util.Util.changeImg;
import static secret.hehe.com.secret.Util.Util.doSelect;
import static secret.hehe.com.secret.Util.Util.doUpdate;


public class LoginActivity extends AppCompatActivity {


    private EditText id;
    private EditText pwd;
    private CheckBox remember_pwd;
    private String jsonString;
    private int icon=0;
    private int canClick=1;
    private ImageView imageView;
    private AlertDialog loging;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //防止杀死变量
        if (savedInstanceState != null) {
            try {
                icon = savedInstanceState.getInt("icon");
                canClick = savedInstanceState.getInt("canClick");
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        //Android6.0后读写sd卡权限需要动态申请
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    2000);
        }

        id=(EditText)findViewById(R.id.user_text);
        pwd=(EditText)findViewById(R.id.pwd_text);
        remember_pwd=(CheckBox)findViewById(R.id.remember_pwd);
        imageView=(ImageView)findViewById(R.id.login_head);

        //勾选记住密码后显示账号密码
        String where = "pwd!=''";
        JSONObject jsonObject =(JSONObject) doSelect("user",where,getApplicationContext()).opt(0);
        try {
            id.setText(jsonObject.getString("id"));
            pwd.setText(jsonObject.getString("pwd"));
            icon =jsonObject.getInt("icon");
            remember_pwd.setChecked(true);
            jsonObject.put("pwd","");
            JSONArray jsonArray = new JSONArray();
            jsonArray.put(jsonObject);
            doUpdate("user",jsonArray,getApplicationContext());
        }catch (Exception e){
            e.printStackTrace();
        }

        changeImg(icon,imageView,getApplicationContext());
        //登录事件
        Button login_button = (Button) findViewById(R.id.login_button);
        login_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(canClick==1){
                    canClick=0;
                    if(loging ==null){
                        loging = new AlertDialog.Builder(LoginActivity.this).setTitle("提示")//设置对话框标题
                                .setMessage("登录中")//设置显示的内容
                                .setCancelable(false)
                                .show();
                    }
                    String params = "id=" + URLEncoder.encode(id.getText().toString()) + "&pwd=" +
                            URLEncoder.encode(pwd.getText().toString());
                    Util util = new Util();
                    Util.postThread loginThread = util.new postThread("/user/login",getApplicationContext(),params,handler,1);
                    loginThread.start();
                }else{
                    return;
                }
            }
        });
        //更换账号
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, SearchMailActivity.class);
                intent.putExtra("isMail",0);
                startActivityForResult(intent,1001);
            }
        });

        //去注册页面
        TextView textView = (TextView) findViewById(R.id.toRegister);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toRegister();
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //保存变量
        super.onSaveInstanceState(outState);
        outState.putInt("icon", icon);
        outState.putInt("canClick", canClick);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //刷新信息
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == 1000) {
            try {
                String uid = (String)data.getSerializableExtra("userId");
                id.setText(uid);
                pwd.setText("");
                icon =(int) data.getSerializableExtra("icon");
                changeImg(icon,imageView,getApplicationContext());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 2000) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                //Toast.makeText(StartActivity.this, "申请成功", Toast.LENGTH_SHORT).show();
            } else {
                // Permission Denied
                Toast.makeText(LoginActivity.this, "可能导致部分功能无法运作", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void login() {

        //登陆成功页面跳转
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        //intent.putExtra();
        intent.putExtra("userId",id.getText().toString());
        intent.putExtra("icon",icon);
        startActivity(intent);
        finish();
    }

    public void toRegister() {
        //跳转注册页面
        Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
        //intent.putExtra();
        startActivity(intent);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //相应接受数据
            if (msg.what == 1) {
                try{
                    jsonString = msg.obj.toString();
                    JSONObject jsonObject = new JSONObject(jsonString);
                    int code = jsonObject.getInt("code");
                    if(code==200){//登陆成功
                        canClick=1;
                        JSONObject userInfo = new JSONObject(jsonObject.getString("data"));
                        userInfo.remove("uid");
                        if(!remember_pwd.isChecked())
                            userInfo.put("pwd","");
                        JSONArray jsonArray = new JSONArray();
                        jsonArray.put(userInfo);
                        doUpdate("user",jsonArray,getApplicationContext());
                        icon = userInfo.getInt("icon");
                        if(loging!=null){
                            loging.dismiss();
                            loging=null;
                        }
                        login();
                    }else{
                        canClick=1;
                        if(loging!=null){
                            loging.dismiss();
                            loging=null;
                        }
                        Toast.makeText(LoginActivity.this, "密码输入错误或账号不存在", Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    canClick=1;
                    e.printStackTrace();
                }
            }
            if (msg.what == 0) {
                canClick=1;
                if(loging!=null){
                    loging.dismiss();
                    loging=null;
                }
                Toast.makeText(LoginActivity.this, "无网络或访问服务器出错", Toast.LENGTH_SHORT).show();
            }
        }
    };


}
